package com.zhijian.wharf.config;

import com.zhijian.wharf.entity.po.AisPosition;
import com.zhijian.wharf.enums.AisEnum;
import com.zhijian.wharf.service.impl.AisPositionServiceImpl;
import com.zhijian.wharf.util.ApplicationContextHelperCloud;
import dk.tbsalling.aismessages.AISInputStreamReader;
import dk.tbsalling.aismessages.ais.messages.PositionReport;
import dk.tbsalling.aismessages.ais.messages.types.AISMessageType;
import dk.tbsalling.aismessages.ais.messages.types.NavigationStatus;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Component
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private static EchoServerHandler echoServerHandler;

    @PostConstruct
    public void init() {
        echoServerHandler = this;
    }

    private String hex = "";

    /*
     * channelAction
     *
     * channel 通道 action 活跃的
     *
     * 当客户端主动链接服务端的链接后，这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
     *
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道已激活！");
    }

    /*
     * channelInactive
     *
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     *
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃！");
        // 关闭流

    }

//    /**
//     * @param buf
//     * @return
//     * @author dahua
//     * TODO  此处用来处理收到的数据中含有中文的时  出现乱码的问题
//     * 2017年8月31日 下午7:57:28
//     */
//    private String getMessage(ByteBuf buf) {
//        byte[] con = new byte[buf.readableBytes()];
//        buf.readBytes(con);
//        try {
//            return new String(con, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    /**
     * 功能：读取服务器发送过来的信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //todo测试数据
//        String s = "!AIVDM,1,1,,A,16:9oS00008Jpn@FCcdDnhcd08P0,0*1D";
//        String s1 = "!AIVDM,1,1,,B,15MwksP000G@6TDEa501Uc5P08Cq,0*3B";
        try {
            ByteBuf buf = (ByteBuf) msg;
            //创建目标大小的数组
            byte[] barray = new byte[buf.readableBytes()];
            //把数据从bytebuf转移到byte[]
            buf.getBytes(0, barray);
            InputStream inputStream = new ByteArrayInputStream(barray);
            AISInputStreamReader streamReader = new AISInputStreamReader(inputStream, aisMessage -> {
                System.out.println("Received AIS message from MMSI " + aisMessage.getSourceMmsi().getMMSI() + ": " + aisMessage);
                AISMessageType messageType = aisMessage.getMessageType();
                if (messageType == AISMessageType.PositionReportClassAScheduled) {
                    PositionReport positionReport = (PositionReport) aisMessage;
                    AisPosition ais = new AisPosition();
                    ais.setMssi(positionReport.getSourceMmsi().getMMSI().toString());
                    ais.setLongitude(positionReport.getLongitude().toString());
                    ais.setLatitude(positionReport.getLatitude().toString());
                    NavigationStatus navigationStatus = positionReport.getNavigationStatus();
                    ais.setNavigationStatus(AisEnum.NavigationStatusEnum.getByCode(navigationStatus.getCode() + "").getContent());
                    ais.setSog(positionReport.getSpeedOverGround() + "");
                    ais.setTrueHeading(positionReport.getTrueHeading() + "");
                    ais.setSecond(positionReport.getSecond());
                    ApplicationContextHelperCloud.getBean(AisPositionServiceImpl.class).insert(ais);
                }
            }
            );
            streamReader.run();
//            System.out.println(streamReader.toString());
//            String str = hex(barray);
//            hex = str;
//            System.out.println("读取服务器发送过来的信息" + str);
            buf.release();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }


    public static String hex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte aByte : bytes) {
            result.append(String.format("%02x", aByte));
            // upper case
            // result.append(String.format("%02X", aByte));
        }
        return result.toString();
    }


    /**
     * 功能：读取完毕客户端发送过来的数据之后的操作
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {


//        writeMessage(ctx,getHexBytes(str));
//        ctx.writeAndFlush().addListener(ChannelFutureListener.CLOSE);
    }

    /*
      obj：byte数组
    */
    public void writeMessage(ChannelHandlerContext ctx, String receiveStr) {

    }

    /**
     * 功能：服务端发生异常的操作
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息：\r\n" + cause.getMessage());
    }

}
